package com.summer.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.summer.entity.TbDocument;

import com.summer.entity.TbUserinfo;
import com.summer.mapper.TbDocumentMapper;

import com.summer.utils.JwtToken;
import com.summer.utils.MyUtil;
import com.summer.utils.ResponseEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.util.UUID;

/**
 * <p>
 *  前端控制器前端控制器未测试
 * </p>
 *
 * @author summer502
 * @since 2021-03-31
 */
@CrossOrigin
@RestController
@RequestMapping("/tb-document")
@Transactional
@Api(value = "TbDocumentController", description = "活动文档api")

public class TbDocumentController {
    Boolean flag;
    MyUtil myUtil = new MyUtil();
    @Autowired(required = false)
    TbDocumentMapper tbDocumentMapper;
    /**
     * 管理员活动ppt上传
     *
     * @param request
     * @param Authorization
     * @param response
     * @return
     * @throws IOException
     * @throws ParseException
     */
    @ApiOperation("管理员活动文档上传")
    @PostMapping("/web/AddDocument")
    @ResponseBody
    public ResponseEntity AddDocument(@RequestParam(required = true) MultipartFile documentUrl,
                                     @RequestParam(required = false) String documentDescription,
                                     @RequestParam(required = true) int activityId,
                                     HttpServletRequest request,
                                     @RequestHeader String Authorization,
                                     HttpServletResponse response) throws IOException, ParseException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        ResponseEntity responseEntity;
        String token = Authorization;
        //通过token解密出来的user对象
        TbUserinfo user = JwtToken.unsign(token, TbUserinfo.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        if (user.getRoleId()!=1){
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg","权限错误");
            responseEntity.putDataValue("timestamp",myUtil.getTime());
            return responseEntity;
        }
        //图片资源访问路径
        String fileLocation = "/static/restaurantRes/";
        //获取提交文件名称
        String filename = documentUrl.getOriginalFilename();
        String newfilename = System.currentTimeMillis() + UUID.randomUUID().toString().replace(".", "").substring(0, 6) + "." + filename.substring(filename.lastIndexOf(".") + 1);

        //定义上传文件存放的路径
        String path = request.getSession().getServletContext().getRealPath(fileLocation);//此处为tomcat下的路径，服务重启路径会变化
        System.out.println(path);
        //返回保存的url，根据url可以进行文件查看或者下载
        String filePath = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort() //端口 https443端口无需添加
                + fileLocation + newfilename;

        String head_portrait = filePath;//根路径+文件名
        File file = new File("/www/javaweb/propaganda_system/picture/" + newfilename);
        TbDocument tbDocument = new TbDocument();
        tbDocument.setDocumentUrl(head_portrait);
        tbDocument.setActivityId(activityId);
        tbDocument.setDocumentDescription(documentDescription);
//            //修改信息
//            pictureDao.updateById(picture);
        tbDocumentMapper.insert(tbDocument);
        documentUrl.transferTo(file);
        responseEntity = ResponseEntity.ok();
        TbDocument tbDocument1=tbDocumentMapper.selectById(tbDocument.getDocumentId());
        responseEntity.putDataValue("tbDocument1",tbDocument1);
        System.out.println("加分证明上传成功");
        return responseEntity;
    }
    /**
     * 活动文档下载
     * @param picture_id
     * @return
     */
    @ApiOperation("活动文档下载")
    @PostMapping("/web/loaderDocument")
    @ResponseBody
    public ResponseEntity loaderDocument(HttpServletResponse response,@RequestParam(required = true) Integer picture_id) throws IOException {
        ResponseEntity responseData = null;
        QueryWrapper<TbDocument> queryWrapper = new QueryWrapper<>();
        int is_delete = 0;
        queryWrapper.eq("is_delete", is_delete);
        queryWrapper.eq("picture_id", picture_id);
        TbDocument picture = tbDocumentMapper.selectOne(queryWrapper);
        if (picture != null) {
            String picture_path = picture.getDocumentUrl();
            String image = picture_path.substring(picture_path.lastIndexOf("/") + 1);
            String newPicture_path = "/www/javaweb/propaganda_system/picture/" + image;
//        response.setHeader("content-type", "application/octet-stream");
//        response.setContentType("application/octet-stream");
            try {
                response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(image, "UTF-8"));
            } catch (UnsupportedEncodingException e2) {
                e2.printStackTrace();
            }
//        FileOutputStream outputStream = new FileOutputStream(new File("图片.jpg"));
            OutputStream outputStream = response.getOutputStream();
            FileInputStream fileInputStream = new FileInputStream(newPicture_path);

            byte[] bytes = new byte[1024];
            int len;
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.close();
            fileInputStream.close();
            responseData = ResponseEntity.ok();
            responseData.putDataValue("msg", "下载成功");
            return responseData;
        } else {
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg", "文档不存在无法下载");
            return responseData;
        }
    }

    /**
     * 根据document_id查询文档信息
     * @param document_id
     * @return
     * @throws IOException
     */
    @ApiOperation("根据document_id查询文档信息")
    @PutMapping("/web/selectByDocumentId")
    @ResponseBody
    public ResponseEntity selectByDocumentId(@RequestParam(required = true) Integer document_id) throws IOException {
        ResponseEntity responseEntity;
        responseEntity=ResponseEntity.ok();
        int is_delete = 0;
        QueryWrapper<TbDocument> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", is_delete);
        queryWrapper.eq("document_id", document_id);
        TbDocument tbDocument=tbDocumentMapper.selectOne(queryWrapper);
        responseEntity.putDataValue("Document",tbDocument);
        return responseEntity;

    }

    /**
     * 文档删除
     * @param Authorization
     * @param document_id
     * @return
     * @throws IOException
     */
    @ApiOperation("文档删除")
    @PostMapping("/web/deleteDocument")
    @ResponseBody
    public ResponseEntity deleteDocument(@RequestHeader String Authorization, @RequestParam(required = true) Integer document_id) throws IOException {
        ResponseEntity responseEntity = null;
        String token = Authorization;
        //通过token解密出来的user对象
        TbUserinfo user = JwtToken.unsign(token, TbUserinfo.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        if (user.getRoleId()!=1){
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg","权限错误");
            responseEntity.putDataValue("timestamp",myUtil.getTime());
            return responseEntity;
        }
        int is_delete = 1;
        TbDocument tbDocument = tbDocumentMapper.selectById(document_id);
        tbDocument.setIsDelete(is_delete);
        tbDocumentMapper.updateById(tbDocument);
        responseEntity = ResponseEntity.ok();
        responseEntity.putDataValue("msg", "删除成功");
        return responseEntity;
    }


}
